package m.server.web;

import m.server.web.req.Header;
import m.system.util.GenerateID;
import m.system.util.StringUtil;
import m.system.util.SystemUtil;

public class AuthInfoUtil {
    private static final ThreadLocal<String> session = new ThreadLocal<>();
    private static final ThreadLocal<Request> request = new ThreadLocal<>();
    protected static void release(){
        session.remove();
        request.remove();
    }
    protected static void init(Request req){
        request.set(req);
        String sn=null;
        String authorization=req.getHeader(Header.Authorization);
        if(!StringUtil.isSpace(authorization)) {
            String[] arr=authorization.split(" ");
            if(arr.length>1&&!StringUtil.isSpace(arr[1])&&!arr[1].equals("null")&&!arr[1].equals("undefined")) {
                sn=arr[1];
            }
        }
        if(null==sn){
            Cookie cookie=request.get().getCookie(SESSION_NAME);
            if(null!=cookie){
                sn= cookie.getValue();
            }
        }
        if(null==sn){
            sn="no_cookie_"+ GenerateID.generatePrimaryKey();
            SystemUtil.println("no_cookie");
        }
        session.set(sn);
    }

    /**
     * 线程调用 结束后请调用clear
     */
    public static void reset(Request request){
        if(null==session.get()){
            init(request);
        }
    }
    public static void clear(){release();}
    public static String getSession(){
        String s=session.get();
        if(null==s) throw new RuntimeException("新线程使用AuthInfoUtil需先初始化，请调用AuthInfoUtil.reset方法设置。");
        return s;
    }
    public static Request getRequest(){
        Request r=request.get();
        if(null==r) throw new RuntimeException("新线程使用AuthInfoUtil需先初始化，请调用AuthInfoUtil.reset方法设置。");
        return r;
    }

    public final static String SESSION_NAME="m_session";

}
